﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.ComponentModel;

namespace Entity
{
    /// <summary>
    /// 实体层扩展方法
    /// </summary>
    public class ExtendMethods
    {
        /// <summary>
        /// 填充某模型的 DisplayName 属性
        /// </summary>
        /// <param name="type"></param>
        /// <param name="displayNames"></param>
        public static void FillDisplayNameAttribute(Type type, IDictionary<string, string> displayNames)
        {
            if (type == null || displayNames == null || displayNames.Count == 0)
            {
                return;
            }
            PropertyInfo targetProperty = typeof(MemberDescriptor).GetProperty("AttributeArray", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance);
            string displayName;
            foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(type))
            {
                if (displayNames.TryGetValue(property.Name, out displayName) == false)
                {
                    continue;
                }

                List<Attribute> attributeList = new List<Attribute>(targetProperty.GetValue(property, null) as Attribute[]);
                attributeList.RemoveAll(delegate(Attribute attrib)
               {

                   return attrib is DisplayNameAttribute;

               });
                attributeList.Add(new DisplayNameAttribute(displayName));
                targetProperty.SetValue(property, attributeList.ToArray(), null);
            }

        }
    }
}
